package com.android.huimeiqupin.fragment.group;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.huimeiqupin.MainActivity;
import com.android.huimeiqupin.R;
import com.android.huimeiqupin.activity.BaseObject;
import com.android.huimeiqupin.activity.BaseWeb;
import com.android.huimeiqupin.activity.MainRecommendType;
import com.android.huimeiqupin.activity.MainTab;
import com.android.huimeiqupin.activity.mine.LoginActivity;
import com.android.huimeiqupin.enums.EJumpStatus;
import com.android.huimeiqupin.fragment.BaseLazyFragment;
import com.android.huimeiqupin.model.MainTabData;
import com.android.huimeiqupin.model.detail.Banner;
import com.android.huimeiqupin.model.group.AdPictureData;
import com.android.huimeiqupin.model.group.AdPictureDataCallback;
import com.android.huimeiqupin.model.group.MainList;
import com.android.huimeiqupin.model.group.MainListCallback;
import com.android.huimeiqupin.model.group.MainSpreadData;
import com.android.huimeiqupin.model.group.MainSpreadDataCallback;
import com.android.huimeiqupin.model.group.MainTab_Nav;
import com.android.huimeiqupin.model.group.MainTab_NavCallback;
import com.android.huimeiqupin.model.group.MainThematicActivity_Insert;
import com.android.huimeiqupin.model.group.MainThematicActivity_InsertCallback;
import com.android.huimeiqupin.model.member.TopicGoodsData;
import com.android.huimeiqupin.model.member.TopicGoodsDataCallback;
import com.android.huimeiqupin.pojo.BannerUintPojo;
import com.android.huimeiqupin.utils.ConstantsUrl;
import com.android.huimeiqupin.utils.HttpUtils;
import com.android.huimeiqupin.utils.JumpUtils;
import com.android.huimeiqupin.utils.LoginState;
import com.android.huimeiqupin.utils.MyLog;
import com.android.huimeiqupin.utils.ObjectUtils;
import com.android.huimeiqupin.view.AutoVerticalScrollTextView;
import com.android.huimeiqupin.view.group.VRefreshLayout;
import com.android.huimeiqupin.view.group.ViewPagerIndicator;
import com.android.huimeiqupin.view.recycleview.CustomLoadMoreView;
import com.android.huimeiqupin.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.mcxtzhang.nestlistview.NestFullListView;
import com.mcxtzhang.nestlistview.NestFullListViewAdapter;
import com.mcxtzhang.nestlistview.NestFullViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * App首页
 */

public class Fragment_Group extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {

    @BindView(R.id.click_resetnetwork_msg)
    TextView clickResetnetworkMsg;
    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.main_top_bg)
    Toolbar mainTopBg;

    private View view;
    private FragmentActivity mcontext;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private ArrayList<MainList.MainListdata.Mainlistdata> listdatahot = new ArrayList<>();
    private ArrayList<MainTabData> griddata1 = new ArrayList<>();
    private ArrayList<MainTabData> griddata2 = new ArrayList<>();
    private ArrayList<MainTabData> griddata3 = new ArrayList<>();
    private ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert = new ArrayList<>();
    private MainSpreadData.DataBean.Kill kill = new MainSpreadData.DataBean.Kill();
    private MainSpreadData.DataBean.Spread2 spread2 = new MainSpreadData.DataBean.Spread2();
    private MainSpreadData.DataBean.Spread3 spread3 = new MainSpreadData.DataBean.Spread3();
    private MainSpreadData.DataBean.Spread4 spread4 = new MainSpreadData.DataBean.Spread4();
    private MainSpreadData.DataBean.Spread5 spread5 = new MainSpreadData.DataBean.Spread5();
    private ArrayList<Banner.Bannerdata> Bannerlist = new ArrayList<>();
    private ViewPager bannerpager;
    private ViewPagerIndicator viewPagerIndicator1;
    private ImageView main_ad_iv;
    private AdaptList adapter;
    private VRefreshLayout mRefreshLayout;
    private CustomRecycleView mRecyclerView;
    private RelativeLayout progress;
    private int page = 1;
    private View progress_hot;
    private LinearLayout ll_kill_desc;
    private LinearLayout ll_globalshopping_desc;
    private LinearLayout ll_freeopengroup_desc;
    private LinearLayout ll_crowdfunding_desc;
    private LinearLayout ll_brandclearance_desc;
    private ImageView kill_iv;
    private ImageView globalshopping_iv;
    private ImageView freeopengroup_iv;
    private ImageView crowfunding_iv;
    private ImageView sale_iv;
    private AutoVerticalScrollTextView bulletintitle;
    private AutoVerticalScrollTextView bulletincontent;
    private int retlen;
    private TextView kill_hour;
    private TextView kill_minute;
    private TextView kill_second;
    private LinearLayout main_spread;
    private LinearLayout freeopengroup_ll;
    private LinearLayout crowdfunding_ll;
    private LinearLayout brandclearance_ll;
    private LinearLayout secondkill_ll;
    private LinearLayout globalshopping_ll;
    private int bulletinsize;
    private int number1 = 0;
    private NestFullListView tabrow;
    private NestFullListView sort_grid1;
    private NestFullListView sort_grid2;
    private NestFullListView sort_grid3;
    private TextView progress_hot_tv;
    private LinearLayoutManager mLayoutManager;
    private boolean isRunning = true;
    private GridLayoutManager mGridLayoutManager;
    private TextView refresh_textView;
    private String topicId = "";
    private LinearLayout llHotList;
    private boolean isFirstStart = true;
    private LinearLayout ll_bullet;
    private String nextName;
    private TextView kill_desc;
    private String adAnurl;
    private boolean isFirstRun = true;
    private TextView kill_Title;

    public Fragment_Group() {
    }


    public static Fragment_Group newInstance() {
        Fragment_Group fragment = new Fragment_Group();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //限量秒杀
            case R.id.secondkill_ll:
                BannerUintPojo Apojo = new BannerUintPojo();
                Apojo.return_type = kill.getAnurl();
                Apojo.title = kill.getTp_name();
                Apojo.id = kill.getId();
                if (JumpUtils.jumpToEveryWhere(getActivity(), Apojo, Fragment_Group.this)) return;
                toMainTab(0, 9, kill.getTp_name(), kill.getId() + "");
                break;
            //免单开团
            case R.id.freeopengroup_ll:
                BannerUintPojo Apojo3 = new BannerUintPojo();
                Apojo3.return_type = spread3.getAnurl();
                Apojo3.title = spread3.getTp_name();
                Apojo3.id = spread3.getId();
                if (JumpUtils.jumpToEveryWhere(getActivity(), Apojo3, Fragment_Group.this)) return;
                toObject(spread3.getTp_name(), spread3.getId());
                break;
            //新品预售
            case R.id.crowdfunding_ll:
                BannerUintPojo Apojo4 = new BannerUintPojo();
                Apojo4.return_type = spread4.getAnurl();
                Apojo4.title = spread4.getTp_name();
                Apojo4.id = spread4.getId();
                if (JumpUtils.jumpToEveryWhere(getActivity(), Apojo4, Fragment_Group.this)) return;
                toObject(spread4.getTp_name(), spread4.getId());
                break;
            //底价清仓
            case R.id.brandclearance_ll:
                BannerUintPojo Apojo5 = new BannerUintPojo();
                Apojo5.return_type = spread5.getAnurl();
                Apojo5.title = spread5.getTp_name();
                Apojo5.id = spread5.getId();
                if (JumpUtils.jumpToEveryWhere(getActivity(), Apojo5, Fragment_Group.this)) return;
                toObject(spread5.getTp_name(), spread5.getId());
                break;
            //全球购
            case R.id.globalshopping_ll:
                BannerUintPojo Apojo2 = new BannerUintPojo();
                Apojo2.return_type = spread2.getAnurl();
                Apojo2.title = spread2.getTp_name();
                if (JumpUtils.jumpToEveryWhere(getActivity(), Apojo2, Fragment_Group.this)) return;
                changeTab(2);
                break;
            //广告图
            case R.id.main_ad_iv:
                if (!TextUtils.isEmpty(adAnurl)) {
                    BannerUintPojo ApojoAD = new BannerUintPojo();
                    ApojoAD.return_type = adAnurl;
                    if (JumpUtils.jumpToEveryWhere(getActivity(), ApojoAD, Fragment_Group.this))
                        return;
                }
//                Intent intent = new Intent(getActivity(), BaseObject.class);
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "专题活动");
//                intent.putExtra("topicname", "专题活动");
//                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, topicId);
//                startActivity(intent);
                break;
            //热议
            case R.id.bulletintitle:
                String common_id = (String) bulletintitle.getTag();
                Intent intent_tuan = new Intent(mcontext, BaseObject.class);
                intent_tuan.putExtra("title", "团详情");
                intent_tuan.putExtra("need_id", common_id + "");
                mcontext.startActivity(intent_tuan);
                break;
            //产品
            case R.id.bulletincontent:
                String goods_id = (String) bulletincontent.getTag();
                if (!TextUtils.isEmpty(goods_id)) {
                    ObjectUtils.ToDetailActivity(mcontext, 1, goods_id, "");
                }
                break;
        }
    }

    private Handler handler = new Handler() {

        private int index;

        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                bulletintitle.next();
                bulletincontent.next();
                number1++;
                index = number1 % bulletinsize;
                if (square.size() > index) {
                    MainSpreadData.DataBean.SquareBean squareBean = square.get(index);
                    bulletintitle.setText(squareBean.getSquare_desc());
                    bulletintitle.setTag(squareBean.getCommon_id());
                    bulletincontent.setText(squareBean.getGoods_name());
                    bulletincontent.setTag(squareBean.getGoods_id());
                }
            }
        }
    };

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                if (retlen > 0) {
                    String hour = String.format("%02d", retlen / 3600);
                    String minute = String.format("%02d", retlen % 3600 / 60);
                    String second = String.format("%02d", retlen % 60);
                    kill_hour.setText(hour);
                    kill_minute.setText(minute);
                    kill_second.setText(second);
                    retlen--;
                }
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {

        }
    }

    @Override
    protected void initPrepare() {
        ininData();
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            getMainTab_Nav();
            GetDataListData(page);
            GetDataBanner();
            GetDataAdPic();
            GetHotListData();
            getMainSpread();
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.layout_recycle_refresh, container, false);
        ButterKnife.bind(this, view);
        mcontext = getActivity();
        mainTopBg.setVisibility(View.GONE);
        new Thread() {
            @Override
            public void run() {
                while (isRunning) {
                    SystemClock.sleep(1000);
                    handler1.sendEmptyMessage(1);
                }
            }
        }.start();
        ininData();
        initUI();
        return view;
    }

    private void ininData() {
        getMianThematic_Insert();
    }

    /**
     * 控件初始化
     */
    private void initUI() {
        mRefreshLayout = (VRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
        mRecyclerView = (CustomRecycleView) view.findViewById(R.id.listView);
        progress = (RelativeLayout) view.findViewById(R.id.progress);
        //轮播图
        View fragment_head = inflater.inflate(R.layout.main_fragment1_head_banner, null, false);
        bannerpager = (ViewPager) fragment_head.findViewById(R.id.bannerpager_fragment);
        viewPagerIndicator1 = (ViewPagerIndicator) fragment_head.findViewById(R.id.viewPagerIndicator1);
        viewPagerIndicator1.autoScroll(getFragmentManager(), bannerpager, 1);
        //广告图
        main_ad_iv = (ImageView) fragment_head.findViewById(R.id.main_ad_iv);
        //首页推广
        kill_hour = (TextView) fragment_head.findViewById(R.id.kill_hour);
        kill_minute = (TextView) fragment_head.findViewById(R.id.kill_minute);
        kill_second = (TextView) fragment_head.findViewById(R.id.kill_second);
        kill_desc = (TextView) fragment_head.findViewById(R.id.spread_kill_desc);
        kill_Title = (TextView) fragment_head.findViewById(R.id.spread_kill_title);
        ll_kill_desc = (LinearLayout) fragment_head.findViewById(R.id.ll_kill_desc);
        ll_globalshopping_desc = (LinearLayout) fragment_head.findViewById(R.id.ll_globalshopping_desc);
        ll_freeopengroup_desc = (LinearLayout) fragment_head.findViewById(R.id.ll_freeopengroup_desc);
        ll_crowdfunding_desc = (LinearLayout) fragment_head.findViewById(R.id.ll_crowdfunding_desc);
        ll_brandclearance_desc = (LinearLayout) fragment_head.findViewById(R.id.ll_brandclearance_desc);
        kill_iv = (ImageView) fragment_head.findViewById(R.id.kill_iv);
        globalshopping_iv = (ImageView) fragment_head.findViewById(R.id.globalshopping_iv);
        freeopengroup_iv = (ImageView) fragment_head.findViewById(R.id.freeopengroup_iv);
        crowfunding_iv = (ImageView) fragment_head.findViewById(R.id.crowfunding_iv);
        sale_iv = (ImageView) fragment_head.findViewById(R.id.sale_iv);
        freeopengroup_ll = (LinearLayout) fragment_head.findViewById(R.id.freeopengroup_ll);
        crowdfunding_ll = (LinearLayout) fragment_head.findViewById(R.id.crowdfunding_ll);
        brandclearance_ll = (LinearLayout) fragment_head.findViewById(R.id.brandclearance_ll);
        secondkill_ll = (LinearLayout) fragment_head.findViewById(R.id.secondkill_ll);
        globalshopping_ll = (LinearLayout) fragment_head.findViewById(R.id.globalshopping_ll);
        main_spread = (LinearLayout) fragment_head.findViewById(R.id.main_spread);

        secondkill_ll.setOnClickListener(this);
        globalshopping_ll.setOnClickListener(this);
        freeopengroup_ll.setOnClickListener(this);
        crowdfunding_ll.setOnClickListener(this);
        brandclearance_ll.setOnClickListener(this);

        //拼团快报
        ll_bullet = (LinearLayout) fragment_head.findViewById(R.id.ll_bullet);
        bulletintitle = (AutoVerticalScrollTextView) fragment_head.findViewById(R.id.bulletintitle);
        bulletincontent = (AutoVerticalScrollTextView) fragment_head.findViewById(R.id.bulletincontent);
        bulletintitle.setOnClickListener(this);
        bulletincontent.setOnClickListener(this);
        //分类+快报
        sort_grid1 = (NestFullListView) fragment_head.findViewById(R.id.main_fragment_grid_sort1);
        sort_grid2 = (NestFullListView) fragment_head.findViewById(R.id.main_fragment_grid_sort2);
        sort_grid3 = (NestFullListView) fragment_head.findViewById(R.id.main_fragment_grid_sort3);
        sort_grid1.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_grid_fragment_sort, griddata1) {
            @Override
            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
                ObjectUtils.photo(mcontext, testBean.getImg(), ((ImageView) holder.getView(R.id.item_grid_fragment_sort_img)));
            }
        });
        sort_grid2.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_grid_fragment_sort, griddata2) {
            @Override
            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
                ObjectUtils.photo(mcontext, testBean.getImg(), ((ImageView) holder.getView(R.id.item_grid_fragment_sort_img)));

            }
        });

        sort_grid3.setAdapter(new NestFullListViewAdapter<MainTabData>(R.layout.item_grid_fragment_sort, griddata3) {
            @Override
            public void onBind(int position, MainTabData testBean, NestFullViewHolder holder) {
                holder.setText(R.id.item_grid_fragment_sort_tv, testBean.getName());
                ObjectUtils.photo(mcontext, testBean.getImg(), ((ImageView) holder.getView(R.id.item_grid_fragment_sort_img)));

            }
        });
        sort_grid1.setOnItemClickListener(new MainSortStartTo(griddata1));
        sort_grid2.setOnItemClickListener(new MainSortStartTo(griddata2));
        sort_grid3.setOnItemClickListener(new MainSortStartTo(griddata3));
        //水平滚动列表
        tabrow = (NestFullListView) fragment_head.findViewById(R.id.grid);
        llHotList = (LinearLayout) fragment_head.findViewById(R.id.ll_hot_list);
        progress_hot = fragment_head.findViewById(R.id.progress_hot);
        progress_hot_tv = (TextView) fragment_head.findViewById(R.id.progress_hot_tv);
        initTab();
        initRecycle(fragment_head);
        ReFreshData();
        main_ad_iv.setOnClickListener(this);
    }

    private void initRecycle(View head) {
        adapter = new AdaptList(mcontext, null, "0");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        adapter.addHeaderView(head);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
//        ((TextView) view.findViewById(R.id.scroll_total)).setText();
        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 1);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.main_list_item_go_kai:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 分类跳转
     */
    class MainSortStartTo implements NestFullListView.OnItemClickListener {
        ArrayList<MainTabData> griddata;

        public MainSortStartTo(ArrayList<MainTabData> griddata) {
            this.griddata = griddata;
        }

        @Override
        public void onItemClick(NestFullListView nestFullListView, View view, int position) {
            MainTabData pojo = griddata.get(position);
            nextName = pojo.getName();

            BannerUintPojo Apojo = new BannerUintPojo();
            Apojo.return_type = pojo.getAnurl();
            Apojo.title = pojo.getName();
            if (JumpUtils.jumpToEveryWhere(getActivity(), Apojo, Fragment_Group.this)) return;

            switch (nextName) {
                case "品质严选":
                    break;
                case "品牌折扣":
                case "地道中国":
                case "特色中国":
                    toObject(nextName, "");
                    break;
                case "高佣推广":
                    toMainTab(0, 8, nextName);
                    break;
                case "热销榜":
                    toObject(nextName, "");
                    break;
                case "新品热销":
                    changeTab(1);
                    break;
                case "同城新零售":
                case "同城":
                case "同城购":
                case "同城商品":
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.JumptoSameCity(EJumpStatus.EnumSameCity.getRegmatch(), nextName);
                    break;
                case "秒杀团":
                case "限时秒拼":
                    toMainTab(0, 3, nextName);
                    break;
                case "品牌团":
                    toObject(nextName, "");
                    break;
                case "海淘团":
                case "全球购":
                    changeTab(2);
                    break;
                case "附近商家":
                    if (LoginState.getInstance().isLogin(mcontext)) {
                        toWeb(ConstantsUrl.baseDomain + "store/nearby");
                    } else {
                        startActivity(new Intent(mcontext, LoginActivity.class));
                    }
                    break;
                case "店铺街":
                    toObject(nextName, "");
                    break;
                case "9.9元包邮":
                case "9.9包邮":
                case "9.9特卖":
                    toObject(nextName, "");
                    break;
                case "优惠券":
                    if (LoginState.getInstance().isLogin(mcontext)) {
                        toWeb(ConstantsUrl.baseDomain + "coupon/receive_center");
                    } else {
                        startActivity(new Intent(mcontext, LoginActivity.class));
                    }
                    break;
                default:
                    Intent intent = new Intent(mcontext, MainRecommendType.class);
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_TITLE, griddata.get(position).getName());
                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_SORT_SHOW_LINK, griddata.get(position).getId());
                    startActivity(intent);
                    break;
            }
        }
    }

    private void toWeb(String url) {
        Intent intent = new Intent(getActivity(), BaseWeb.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_WEB_URL, url);
        startActivity(intent);
    }

    private void changeTab(int position) {
        MainActivity A = (MainActivity) getActivity();
        A.ChangeMainFragment(position);
    }

    private void toObject(String title, String id) {
        Intent intent = new Intent(mcontext, BaseObject.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, title);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, id);
        startActivity(intent);
    }

    private void toMainTab(int position, int type, String title) {
        toMainTab(position, type, title, "");
    }

    private void toMainTab(int position, int type, String title, String sortID) {
        Intent intent = new Intent(mcontext, MainTab.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, position);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, type);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, title);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_RATE_ID, sortID);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SECONDKILL_TIME, retlen);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 1:
                String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
                if (!TextUtils.isEmpty(zone) && !zone.equals("0")) {
                    toObject(nextName, "");
                }
                break;
        }
    }

    /**
     * 热门活动
     */
    private void initTab() {
        //        //动态设置选项卡宽度，超过2个可以滑动查看
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int width = (int) (metrics.widthPixels / 2.5);
        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
        tabrow.setAdapter(new NestFullListViewAdapter<MainList.MainListdata.Mainlistdata>(R.layout.list_main_hor_adapter, listdatahot) {
            @Override
            public void onBind(int position, MainList.MainListdata.Mainlistdata testBean, NestFullViewHolder holder) {
                (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
                ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                String price1 = testBean.getTeam_price();
                SpannableString msp = new SpannableString("￥" + price1);
                msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
                holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getPrice());
                holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
                ObjectUtils.photo2(mcontext, testBean.getThumb(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));
            }
        });
        tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
            @Override
            public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                ObjectUtils.ToDetailActivity(mcontext, 1, listdatahot.get(pos).getId(), "");
            }
        });
    }

    /**
     * 刷新
     */
    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                GetDataBanner();
                                GetDataAdPic();
                                GetDataListData(page);
                                GetHotListData();
                                getMainTab_Nav();
                                getMainSpread();
                                // getMianThematic_Insert();
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        getMianThematic_Insert();
        GetDataBanner();
        GetDataAdPic();
        GetDataListData(page);
        GetHotListData();
        getMainTab_Nav();
        getMainSpread();
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page);
    }

    /**
     * 轮播图销毁开启
     */
    @Override
    public void onStart() {
        super.onStart();
        viewPagerIndicator1.setVisible(true);
    }

    @Override
    public void onPause() {
        super.onPause();
        viewPagerIndicator1.setVisible(false);
    }

    /**
     * 专题活动插入信息
     */
    private void getMianThematic_Insert() {
        String address = ConstantsUrl.domain + ConstantsUrl.MAINTHMATIC_INSERT;
        HashMap<String, String> map = new HashMap<>();
        map.put("posid", "1");
        HttpUtils.get(address, map, new MainThematicActivity_InsertCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(MainThematicActivity_Insert response, int id) {
                if (response == null) {
                    return;
                }
                ta_insert.clear();
                MainThematicActivity_Insert.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getList())) {
                    ta_insert.addAll(data.getList());
                    mRecyclerView.setLayoutManager(mLayoutManager);
                    mRecyclerView.setAdapter(adapter);
                }
            }
        });
    }

    /**
     * 首页推广
     */
    private void getMainSpread() {
        String address = ConstantsUrl.domain + ConstantsUrl.MAINTAB_MAINSPREAD;
        HttpUtils.get(address, null, spreadDataCallback);
    }

    private List<MainSpreadData.DataBean.SquareBean> square;
    MainSpreadDataCallback spreadDataCallback = new MainSpreadDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(MainSpreadData response, int id) {
            if (response != null && response.getCode() == 0 && response.getData() != null) {
                MainSpreadData.DataBean data = response.getData();
                square = data.getSquare();
                if (ObjectUtils.listHasData(square)) {
                    //拼团快报
                    ll_bullet.setVisibility(View.VISIBLE);
                    bulletinsize = square.size();
                    MainSpreadData.DataBean.SquareBean squareBean = square.get(0);
                    bulletintitle.setText(squareBean.getSquare_desc());
                    bulletintitle.setTag(squareBean.getCommon_id());
                    bulletincontent.setText(squareBean.getGoods_name());
                    bulletincontent.setTag(squareBean.getGoods_id());

                    if (isFirstStart && square.size() > 1) {
                        isFirstStart = false;
                        new Thread() {
                            @Override
                            public void run() {
                                while (isRunning) {
                                    SystemClock.sleep(5000);
                                    handler.sendEmptyMessage(1);
                                }
                            }
                        }.start();
                    }
                } else {
                    ll_bullet.setVisibility(View.GONE);
                }

                kill = data.getKill();
                if (kill == null) {
                    main_spread.setVisibility(View.GONE);
                    return;
                }else {
                    main_spread.setVisibility(View.VISIBLE);
                }
                spread2 = data.getSpread2();
                spread3 = data.getSpread3();
                spread4 = data.getSpread4();
                spread5 = data.getSpread5();

                retlen = kill.getEtime();
                String tp_desc = kill.getTp_desc();
                if (!TextUtils.isEmpty(tp_desc)) {
                    kill_desc.setText(tp_desc + "");
                }
                String tp_name = kill.getTp_name();
                if (!TextUtils.isEmpty(tp_name)) {
                    kill_Title.setText(tp_name);
                }

                //首页推广
                String killId = kill.getId();
                if (TextUtils.isEmpty(killId) || killId.equals("0")) {
                    ll_kill_desc.setVisibility(View.GONE);
                } else {
                    ll_kill_desc.setVisibility(View.VISIBLE);
                }
                ObjectUtils.photo2(mcontext, kill.getThumbs(), kill_iv);

                String spread2Id = spread2.getId();
                if (TextUtils.isEmpty(spread2Id) || spread2Id.equals("0")) {
                    ll_globalshopping_desc.setVisibility(View.GONE);
                } else {
                    ll_globalshopping_desc.setVisibility(View.VISIBLE);
                }
                ObjectUtils.photo2(mcontext, spread2.getThumbs(), globalshopping_iv);

                String spread3Id = spread3.getId();
                if (TextUtils.isEmpty(spread3Id) || spread3Id.equals("0")) {
                    ll_freeopengroup_desc.setVisibility(View.GONE);
                } else {
                    ll_freeopengroup_desc.setVisibility(View.VISIBLE);
                }
                ObjectUtils.photo2(mcontext, spread3.getThumbs(), freeopengroup_iv);

                String spread4Id = spread4.getId();
                if (TextUtils.isEmpty(spread4Id) || spread4Id.equals("0")) {
                    ll_crowdfunding_desc.setVisibility(View.GONE);
                } else {
                    ll_crowdfunding_desc.setVisibility(View.VISIBLE);
                }
                ObjectUtils.photo2(mcontext, spread4.getThumbs(), crowfunding_iv);

                String spread5Id = spread5.getId();
                if (TextUtils.isEmpty(spread5Id) || spread5Id.equals("0")) {
                    ll_brandclearance_desc.setVisibility(View.GONE);
                } else {
                    ll_brandclearance_desc.setVisibility(View.VISIBLE);
                }
                ObjectUtils.photo2(mcontext, spread5.getThumbs(), sale_iv);
            }
        }
    };

    /**
     * 导航分类信息
     */
    private void getMainTab_Nav() {
        String address = ConstantsUrl.domain + ConstantsUrl.MAINTAB_NAV;
        MyLog.e("地址", address);
        HashMap<String, String> map = new HashMap<>();
        map.put("typeid", "1");
        HttpUtils.get(address, map, mainTabNavCallback);
    }

    MainTab_NavCallback mainTabNavCallback = new MainTab_NavCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(MainTab_Nav response, int id) {
            griddata1.clear();
            griddata2.clear();
            griddata3.clear();
            MainTab_Nav.DataBean data = response.getData();
            if (response == null || data == null || !ObjectUtils.listHasData(data.getList())) {
                return;
            }
            List<MainTab_Nav.DataBean.ListBean> list = data.getList();
            int size1, size2, size3 = 0;
//            if (list.size() > 5) {
//                size1 = 5;
//                size2 = list.size();
//            } else {
//                size1 = list.size();
//                size2 = 0;
//            }
            int listSize = list.size();
            if (listSize < 6) {
                size1 = listSize;
                size2 = 0;
                size3 = 0;
            } else if (listSize < 11) {
                size1 = 5;
                size2 = listSize;
                size3 = 0;
            } else {
                size1 = 5;
                size2 = 10;
                if (listSize > 15) {
                    size3 = 15;
                } else {
                    size3 = listSize;
                }
            }
            for (int i = 0; i < size1; i++) {
                MainTab_Nav.DataBean.ListBean listBean = list.get(i);
                griddata1.add(new MainTabData(listBean.getTitle(), i + 1 + "", listBean.getImg(), listBean.getAnurl()));
            }
            for (int i = 5; i < size2; i++) {
                MainTab_Nav.DataBean.ListBean listBean = list.get(i);
                griddata2.add(new MainTabData(listBean.getTitle(), i + 1 + "", listBean.getImg(), listBean.getAnurl()));
            }
            for (int i = 10; i < size3; i++) {
                MainTab_Nav.DataBean.ListBean listBean = list.get(i);
                griddata3.add(new MainTabData(listBean.getTitle(), i + 1 + "", listBean.getImg(), listBean.getAnurl()));
            }
            sort_grid1.updateUI();
            sort_grid2.updateUI();
            sort_grid3.updateUI();
        }
    };

    /**
     * 轮播图
     */
    private void GetDataBanner() {
        String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
        MyLog.e("地址", address);
        HashMap<String, String> map = new HashMap<>();
        map.put("typeid", "1");
        HttpUtils.get(address, map, new AdPictureDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(AdPictureData response, int id) {
                if (response == null) {
                    return;
                }
                Bannerlist.clear();
                AdPictureData.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getAd())) {
                    List<AdPictureData.DataBean.AdBean> adBean = data.getAd();
                    for (int i = 0; i < adBean.size(); i++) {
                        Banner.Bannerdata bannerdata = new Banner.Bannerdata();
                        bannerdata.setThumb(adBean.get(i).getPath());
                        bannerdata.setLink(adBean.get(i).getAnurl());
                        bannerdata.setPath("");
                        Bannerlist.add(bannerdata);
                    }
                    viewPagerIndicator1.setViewPager(Bannerlist);
                    viewPagerIndicator1.setNotifyDataSetChanged();
                    if (isFirstRun) {
                        isFirstRun = false;
                        viewPagerIndicator1.autoScroll(getFragmentManager(), bannerpager, 1);
                    }
                }
            }
        });
    }

    /**
     * 广告图
     */
    private void GetDataAdPic() {
        String address = ConstantsUrl.domain + ConstantsUrl.ADVERTISEPICTURE;
        HashMap<String, String> map = new HashMap<>();
        map.put("typeid", "17");
        HttpUtils.get(address, map, new AdPictureDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(AdPictureData response, int id) {
                if (response == null) {
                    return;
                }
                AdPictureData.DataBean data = response.getData();
                if (data != null && ObjectUtils.listHasData(data.getAd())) {
                    ObjectUtils.photo2(mcontext, data.getAd().get(0).getPath(), main_ad_iv);
                    adAnurl = data.getAd().get(0).getAnurl();
                    if (adAnurl != null) {

                        String[] split = adAnurl.split(":");
                        if (split != null && split.length > 1) {
                            topicId = split[1];
                        }
                    }
                }
            }
        });
    }

    /**
     * 商品列表
     */
    private void GetDataListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.BIDCOMPETITION_ALIST;
            HashMap<String, String> map = new HashMap<>();
            map.put("page", page + "");
            map.put("typeid", "2");
            MyLog.e("address", address);
            HttpUtils.get(address, map, mCallback);
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    TopicGoodsDataCallback mCallback = new TopicGoodsDataCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(TopicGoodsData response, int id) {
            if (response == null) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                return;
            }
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if (response.getCode() == 0) {
                TopicGoodsData.DataBean data = response.getData();
                if (data == null || !ObjectUtils.listHasData(data.getList())) {
                    if (page == 1) {
                        noData.setVisibility(View.VISIBLE);
                    } else {
                        adapter.loadMoreEnd();
                    }
                    return;
                }
                List<TopicGoodsData.DataBean.ListBean> list = data.getList();
                if (page == 1) {
                    adapter.setNewData(list);
                } else {
                    adapter.addData(list);
                    adapter.loadMoreComplete();
                }
            } else {
                if (page == 1) {
                    noData.setVisibility(View.VISIBLE);
                    noDataTv.setText(response.getMsg());
                    noDataTv.setVisibility(View.VISIBLE);
                } else {
                    adapter.loadMoreFail();
                    ObjectUtils.toast(mcontext, response.getMsg());
                }
            }
        }
    };

    /**
     * 水平滑动商品列表
     */
    private void GetHotListData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MAIN_LISTDATA + "?best=1&size=10";
            MyLog.e("地址", address);
            HttpUtils.get(address, null, new MainListCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(MainList response, int id) {
                    if (response == null) {
                        return;
                    }
                    if (response.getCode() == 0 && response.getData() != null) {
                        listdatahot.clear();
                        List<MainList.MainListdata.Mainlistdata> list = response.getData().getList();
                        if (ObjectUtils.listHasData(list)) {
                            llHotList.setVisibility(View.VISIBLE);
                            listdatahot.addAll(list);
                            tabrow.updateUI();
                            tabrow.setVisibility(View.VISIBLE);
                            progress_hot.setVisibility(View.GONE);
                        }
                    }
                }
            });
        }
    }

    public class AdaptList extends BaseMultiItemQuickAdapter<TopicGoodsData.DataBean.ListBean, BaseViewHolder> {
        private String type;
        private FragmentActivity mcontet;
        private int limitposition;

        public AdaptList(Context context, ArrayList<TopicGoodsData.DataBean.ListBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE, R.layout.item_list_main);
        }

        public AdaptList(FragmentActivity context, ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert, List<TopicGoodsData.DataBean.ListBean> data, String type) {
            super(data);
            //  this.datasize = data.size();
            this.type = type;
            addItemType(ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE, R.layout.item_list_main);
        }

        @Override
        protected void convert(BaseViewHolder holder, final TopicGoodsData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.BRANDDISCOUNTMAINITEMTYPE:
                    ((TextView) holder.getView(R.id.item_list_sort_aa_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(mContext, mainlistdata.getThumb(), ((ImageView) holder.getView(R.id.main_list_item_image)));
                    holder.setText(R.id.main_list_item_tuannumber, mainlistdata.getTeam_num() + "人团");
                    holder.setText(R.id.ll_start_soon_num, mainlistdata.getTeam_num() + "人团");
                    holder.setText(R.id.ll_free_num, mainlistdata.getTeam_num() + "人团");
                    holder.setVisible(R.id.main_list_item_go_kai, true);
                    String sellNum = mainlistdata.getSell_num();
                    if (!TextUtils.isEmpty(sellNum) && !sellNum.equals("0")) {
                        holder.setText(R.id.main_list_item_alltuannumber2, "已团" + sellNum + "件");
                    }
                    holder.setText(R.id.main_list_item_title, mainlistdata.getName());
                    String price1 = mainlistdata.getTeam_price();
                    SpannableString msp = new SpannableString("￥" + price1);
                    msp.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.setText(R.id.main_list_item_money_after, msp);
                    /**
                     * 插入专题活动
                     */
                    final int taposition = holder.getAdapterPosition();
                    limitposition = 4 * ta_insert.size();
                    if (mcontext instanceof FragmentActivity) {
                        if (taposition % 4 == 0 && taposition <= limitposition) {
                            TextView hotactivityTitle = (TextView) holder.getView(R.id.hotactivity_title);
                            hotactivityTitle.setText(ta_insert.get(taposition / 4 - 1).getName());
                            holder.getView(R.id.ll_tainsert).setVisibility(View.VISIBLE);
                            holder.getView(R.id.progress_hot).setVisibility(View.INVISIBLE);
                            TextView more_tv = (TextView) holder.getView(R.id.more_tv);
                            //水平滚动列表
                            NestFullListView tabrow = (NestFullListView) holder.getView(R.id.grid);
                            //        //动态设置选项卡宽度，超过2个可以滑动查看
                            DisplayMetrics metrics = new DisplayMetrics();
                            mcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                            int width = (int) (metrics.widthPixels / 2.5);
                            final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.MATCH_PARENT);
                            tabrow.setAdapter(new NestFullListViewAdapter<MainThematicActivity_Insert.DataBean.ListBean.ApplyBean>(R.layout.list_main_hor_adapter, ta_insert.get(taposition / 4 - 1).getApply_list()) {
                                @Override
                                public void onBind(int position, MainThematicActivity_Insert.DataBean.ListBean.ApplyBean testBean, NestFullViewHolder holder) {
                                    (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
                                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                                    String price1 = testBean.getTeam_price();
                                    SpannableString msp = new SpannableString("￥" + price1);
                                    msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
                                    holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getPrice());

                                    holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
                                    ObjectUtils.photo2(mcontext, testBean.getImg_cover(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));

                                }
                            });

                            tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
                                @Override
                                public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
                                    ObjectUtils.ToDetailActivity(mcontext, 1, ta_insert.get(taposition / 4 - 1).getApply_list().get(pos).getGoods_id(), "");
                                }
                            });
                            more_tv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent intent = new Intent(mcontext, BaseObject.class);
                                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, ta_insert.get(taposition / 4 - 1).getId());
                                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "专题活动");
                                    intent.putExtra("topicname", ta_insert.get(taposition / 4 - 1).getName());
                                    mcontext.startActivity(intent);
                                }
                            });

                        } else {
                            holder.getView(R.id.ll_tainsert).setVisibility(View.GONE);
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }

}
